import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:music_app/api/mock_api.dart';
import 'package:music_app/widget/my_cached_network_image.dart';

class MyView extends StatefulWidget {
  const MyView({super.key});

  @override
  State<MyView> createState() => _MyViewState();
}

class _MyViewState extends State<MyView> with SingleTickerProviderStateMixin {
  var _info = {};
  late TabController _tabController;
  final ScrollController _scrollController = ScrollController();

  Color _getIconColor(double shrinkOffset) {
    // 计算颜色渐变（可调节颜色和阈值）
    double opacity = (shrinkOffset / (300 - kToolbarHeight)).clamp(0, 1);
    return Color.lerp(Colors.white, Colors.black, opacity)!;
  }

  @override
  void initState() {
    super.initState();
    getData();
    // 创建 TabController，指定标签数量和 vsync
    _tabController = TabController(
      length: 3, // 标签数量
      vsync: this, // 动画同步
      initialIndex: 0, // 初始选中的标签索引
    );
  }

  Future<void> getData() async {
    try {
      final response = await MockApi.fetchUser();
      final Map<String, dynamic> info = {
        'account': response['data']['account'],
        'profile': response['data']['profile'],
      };
      print(info);
      setState(() {
        _info = info;
      });
    } catch (e) {
      setState(() {
        _info = {};
      });
    } finally {}
  }

  @override
  void dispose() {
    // 销毁控制器释放资源
    _tabController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // 去掉底部导航栏
      body: CustomScrollView(
        controller: _scrollController,
        physics: const BouncingScrollPhysics(), // 有回弹效果
        slivers: [
          SliverAppBar(
            expandedHeight: 300,
            pinned: true,
            stretch: true, // 下拉可拉伸
            flexibleSpace: LayoutBuilder(
              builder: (context, constraints) {
                final shrinkOffset = constraints.maxHeight;
                final iconColor = _getIconColor(300 - shrinkOffset);

                return Stack(
                  fit: StackFit.expand,
                  children: [
                    FlexibleSpaceBar(
                      stretchModes: const [
                        StretchMode.zoomBackground,
                      ],
                      background: Stack(
                        fit: StackFit.expand,
                        children: [
                          MyCachedNetworkImage(
                            imageUrl: _info['profile']['avatarUrl'],
                            x: 600,
                            y: 600,
                          ),
                        ],
                      ),
                    ),
                    // 前景内容：Title + 按钮颜色变化
                    Positioned(
                      left: 0,
                      right: 0,
                      top: MediaQuery.of(context).padding.top,
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          IconButton(
                            icon: Icon(Icons.menu, color: iconColor),
                            onPressed: () {},
                          ),
                          Text(
                            '+ 添加状态',
                            style: TextStyle(
                              color: iconColor,
                              fontSize: 12,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                          Row(
                            children: [
                              IconButton(
                                icon: Icon(Icons.search, color: iconColor),
                                onPressed: () {},
                              ),
                              IconButton(
                                icon: Icon(Icons.more_vert, color: iconColor),
                                onPressed: () {},
                              ),
                            ],
                          ),
                        ],
                      ),
                    ),
                    // 用户头像名称
                    Positioned(
                      top: 120,
                      left: 0,
                      right: 0,
                      child: Column(
                        children: [
                          ClipRRect(
                            borderRadius: BorderRadius.circular(24),
                            child: MyCachedNetworkImage(
                              imageUrl: _info['profile']['avatarUrl'],
                              x: 180,
                              y: 180,
                              width: 48,
                              height: 48,
                            ),
                          ),
                          const SizedBox(
                            height: 12,
                          ),
                          Text(
                            _info['profile']['nickname'],
                            style: const TextStyle(
                              color: Colors.white,
                              fontSize: 18,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                );
              },
            ),
            leading: Container(),
          ),
          SliverPersistentHeader(
            pinned: true,
            delegate: _SliverPlayAllHeader(
              height: 48,
              child: _buildTabs(),
            ),
          ),
          // SliverFillRemaining自动填充所有的高度
          SliverFillRemaining(
            child: TabBarView(
              controller: _tabController,
              children: [
                _buildMusic(),
                _buildPodcast(),
                _buildNote(),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildMusic() {
    return const Column(
      children: [
        ListItem(
          title: '我喜欢的音乐',
          decoration: '19首 . 250次播放',
          id: 0,
        ),
        ListItem(
          title: '我喜欢的音乐',
          decoration: '19首 . 250次播放',
          id: 0,
        ),
      ],
    );
  }

  Widget _buildPodcast() {
    return const SizedBox(
      child: Text('播客'),
    );
  }

  Widget _buildNote() {
    return const SizedBox(
      child: Text('笔记'),
    );
  }

  Widget _buildTabs() {
    return TabBar(
      // labelColor: Colors.green,
      // 选中文字样式
      labelStyle: const TextStyle(
        color: Color(0xFF000000),
        fontSize: 14,
      ),
      unselectedLabelStyle: const TextStyle(
        fontSize: 14,
        color: Color(0xFF333333),
      ),
      // unselectedLabelColor: const Color(0xFF333333),
      // 选中下划线样式
      // indicatorColor: Colors.black,
      // 重新定义下划线
      indicator: const UnderlineTabIndicator(
        borderSide: BorderSide(
          width: 2,
          color: Color(0xFFf43f3b),
        ),
        // 如果需要调整下划线的位置（比如距离底部的距离），可以使用insets
        insets: EdgeInsets.only(
          bottom: 10,
          left: 6,
          right: 6,
        ), // 距离底部的距离，负值表示向上移动
      ),
      // 设置底部边框线
      dividerColor: Colors.transparent,
      // 绑定tabs控制器
      controller: _tabController,
      tabs: const [
        Tab(text: "音乐"),
        Tab(text: "播客"),
        Tab(text: "笔记"),
      ],
    );
  }
}

class _SliverPlayAllHeader extends SliverPersistentHeaderDelegate {
  final double height;
  final Widget child;

  _SliverPlayAllHeader({
    required this.height,
    required this.child,
  });

  @override
  double get minExtent => height;

  @override
  double get maxExtent => height;

  @override
  Widget build(
      BuildContext context, double shrinkOffset, bool overlapsContent) {
    return Container(
      width: double.infinity,
      color: Colors.white,
      child: child,
    );
  }

  @override
  bool shouldRebuild(covariant _SliverPlayAllHeader oldDelegate) {
    return oldDelegate.child != child || oldDelegate.height != height;
  }
}

class ListItem extends StatelessWidget {
  final int id;
  final String title;
  final String decoration;
  final VoidCallback? onTap;

  const ListItem({
    super.key,
    required this.title,
    required this.decoration,
    this.onTap,
    required this.id,
  });

  @override
  Widget build(BuildContext context) {
    // 音乐播放控制方法
    return InkWell(
      excludeFromSemantics: true,
      onTap: onTap,
      child: Padding(
        padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 16),
        child: Row(
          children: [
            ClipRRect(
              borderRadius: BorderRadius.circular(8),
              child: Container(
                width: 48,
                height: 48,
                color: Colors.grey.shade300,
                child: const Icon(
                  Icons.music_note,
                  color: Colors.white,
                ),
              ),
            ),
            const SizedBox(width: 12),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(
                    title,
                    style: const TextStyle(
                        fontSize: 14, fontWeight: FontWeight.bold),
                    overflow: TextOverflow.ellipsis,
                  ),
                  const SizedBox(height: 4),
                  Row(
                    children: [
                      Expanded(
                        child: Text(
                          decoration,
                          maxLines: 1,
                          style: TextStyle(
                            fontSize: 12,
                            color: Colors.grey.shade600,
                          ),
                          overflow: TextOverflow.ellipsis,
                        ),
                      ),
                    ],
                  )
                ],
              ),
            ),
            GestureDetector(
              onTap: () {},
              child: const Icon(Icons.more_vert),
            )
          ],
        ),
      ),
    );
  }
}
